package okhttp3Demo.interceptor;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.net.SocketTimeoutException;

public class TimeoutRetryInterceptor implements Interceptor {

    public int maxReTryTimes;//最大重试次数
    public long intervalTime;//每次重试时间间隔单位毫秒

    public TimeoutRetryInterceptor(int maxReTryTimes) {
        this.maxReTryTimes = maxReTryTimes;
    }

    public TimeoutRetryInterceptor(int maxReTryTimes, long intervalTime) {
        this.maxReTryTimes = maxReTryTimes;
        this.intervalTime = intervalTime;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        boolean isTimeout = false;//是否是超时标志
        int retryNum = 0;
        do{
            try {
                return chain.proceed(request);
            } catch (SocketTimeoutException e) {
                isTimeout = true;
                retryNum ++;
                if(retryNum <= maxReTryTimes){
                    if(intervalTime > 0){//如果指定重试间隔，则经过指定时间后发起重试
                        try {
                            Thread.sleep(intervalTime);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                    }
                }else throw e;//如果超出最大重试次数，直接抛出异常
            } catch (Exception e){
                isTimeout = false;
                throw e;//非超时异常，直接抛出
            }
        }
        while (isTimeout);
        return null;
    }
}
